$(function () {
  // ************ 图片拖拽
  var params = {
    left: 0,
    top: 0,
    currentX: 0,
    currentY: 0,
    flag: false,
  };

  // 获取相关CSS属性
  var getCss = function (o, key) {
    if (!o) return;
    return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
  };

  // 拖拽的实现
  var startDrag = function (bar, target, callback) {
    if (getCss(target, "left") !== "auto") {
      params.left = getCss(target, "left");
    }
    if (getCss(target, "top") !== "auto") {
      params.top = getCss(target, "top");
    }

    // bar 是拖拽的触发区域
    bar.onmousedown = function (event) {
      params.flag = true;
      if (!event) {
        event = window.event;
        // 防止IE文字选中
        bar.onselectstart = function () {
          return false;
        };
      }

      var e = event;
      params.currentX = e.clientX;
      params.currentY = e.clientY;
    };

    document.onmouseup = function () {
      params.flag = false;
      if (getCss(target, "left") !== "auto") {
        params.left = getCss(target, "left");
      }
      if (getCss(target, "top") !== "auto") {
        params.top = getCss(target, "top");
      }
    };

    document.onmousemove = function (event) {
      var e = event ? event : window.event;
      if (params.flag) {
        var nowX = e.clientX, nowY = e.clientY;
        var disX = nowX - params.currentX, disY = nowY - params.currentY;
        target.style.left = parseInt(params.left) + disX + "px";
        target.style.top = parseInt(params.top) + disY + "px";

        if (typeof callback == "function") {
          callback((parseInt(params.left) || 0) + disX, (parseInt(params.top) || 0) + disY);
        }
        if (event.preventDefault) {
          event.preventDefault();
        }
        return false;
      }
    };
  };

  // **************** 地图放大缩小
  var scale = 10;
  function handleZoom(event) {
    var delta = event.originalEvent.deltaY;

    if (delta > 0) {
      scale--;
    } else {
      scale++;
    }
    scale = Math.min(Math.max(scale, 5), 100);
    $('#zoomImage').css({ transform: 'scale(' + scale / 10 + ')' });
  }

  // ******** 地图底部 legend 菜单切换 ******************
  var mapOptions = [
    {
      title: "现状",
      url: 'img/index/map_completed.jpg'
    },
    {
      title: '高标准农田',
      url: 'img/index/map_total.jpg'
    },
    {
      title: '规划项目',
      url: 'img/index/map_future.jpg'
    }
  ];
  for (var i = 0; i < mapOptions.length; i++) {
    $(".module-switch").append('<li class="fl' + (i === 0 ? " active" : " ") + '">' + mapOptions[i].title + '<i></i></li>');
  }
  $(".module-switch li").click(function () {
    const idx = $(this).index();
    $(this).addClass("active").siblings().removeClass("active");
    $('#dialog-title').html(mapOptions[idx].title);
    $('#myDialog .dialog-context').html(
      '<img id="zoomImage" height="100%" src="' + mapOptions[idx].url + '" alt="' + mapOptions[idx].title + '" />'
    );
    $('#myDialog').show(600);
    $('#dialog-layer').show();
    startDrag(document.getElementById("zoomImage"), document.getElementById("zoomImage"));
  });

  //********************** 地图对话框事件处理 */
  $('#myDialog .dialog-context').on('mousewheel', function (event) {
    event.preventDefault(); // Prevent default scrolling behavior
    handleZoom(event);
  });

  $('.btn-plug').click(function () {
    handleZoom({ originalEvent: { deltaY: -1 } }); // Simulate zoom in
  });

  $('.btn-reduce').click(function () {
    handleZoom({ originalEvent: { deltaY: 1 } }); // Simulate zoom out
  });
  $('.btn-reset').click(function () {
    $('#zoomImage').css({ transform: 'scale(1)' });
  });

  // ************ 地图初始化方法
  function initGeoMap(pointArrayData) {
    $.get('./js/suining_geo.json', function (map) {
      var geoMap = echarts.init(document.getElementById('map'));
      echarts.registerMap("suining", map);
      console.log('------------'+pointArrayData)
      var option = {
        tooltip: {
          trigger: 'item',
          formatter: (e) => {
            // if (e.componentSubType === 'map') {
            //   return ''
            // } else {
            //   const qtl = e.data.shigongdanwei || 0
            //   const fyl = e.data.jianlidanwei || 0
            //   const fzl = e.data.jianliname || 0
            //   return e.name + '<br>' + '气体量: ' + qtl + 'm³' + '<br>' + '废液量: ' + fyl + 't' + '<br>' + '废渣量: ' + fzl + 't'
            // }
            return e.name;
          }
        },
        series: [
          {
            map: "suining",
            type: "map",
            aspectScale: 1,
            selectedMode: 'single',//选择类型,
            hoverable: true,//鼠标经过高亮
            roam: true,//鼠标滚轮缩放
            itemStyle: {
              normal: {
                borderWidth: 1,
                borderColor: '#1ba0f8',//区域边框色
                areaColor: '#23539b',//区域背景色
                label: {
                  show: true,
                  textStyle: {
                    color: '#ffffff',//文字颜色
                    fontSize: 16      //文字大小
                  }
                }
              },
              emphasis: {                 // 选中样式
                borderWidth: 1,
                borderColor: '#00ffff',
                areaColor: '#1ba0f8',//区域背景色
                label: {
                  show: true,
                  textStyle: {
                    color: '#ffffff',//文字颜色
                  }
                }
              }
            }
          },
          {
            type: 'effectScatter',
            coordinateSystem: 'geo',
            z: 5,
            zlevel: 10,
            data: pointArrayData,
            symbolSize: 14,
            label: {
              normal: {
                show: true,
                formatter: function (params) {
                  return params.name;
                },
                position: 'top',
                backgroundColor: '#7c02d0',
                padding: [12, 12],
                borderRadius: 3,
                lineHeight: 26,
                fontSize: 14,
                color: '#ffffff',
                // rich: {
                //   jb: {
                //     padding: [0, 10, 0, 40],
                //     color: '#ff0000',
                //     fontSize: 24
                //   },
                //   yc: {
                //     padding: [0, 10, 0, 40],
                //     color: '#fcc121',
                //     fontSize: 24
                //   },
                //   cz: {
                //     padding: [0, 10, 0, 40],
                //     color: '#ffffff',
                //     fontSize: 24
                //   }
                // }
              },
              emphasis: {
                show: true
              }
            },
            itemStyle: {
              color: '#7c02d0'
            }
          },

        ]
      };
      geoMap.setOption(option);
    });
  }

  // ************ 地图初始化数据拉取 - 异步 ***********************
  function getAllShopList() {
    $.ajax({
      url: 'https://jianliapi.jiashengqizhi.com/m.api',
      type: 'post',
      data: {
        _gp: 'admin.front',
        _mt: 'shopList',
        type: 1,
        page: 1,
        limit: 10000
      },
      contentType: 'application/x-www-form-urlencoded', // 传参格式（默认为表单） json为application/json
      dataType: 'json',
      success: function (res) {
        // 剔除无坐标数据
        var pointArray = res.data
          .filter(item => item.jingdu && item.weidu)
          .map(item => {
            return {
              ...item,
              name: item.shopName,
              value: [item.jingdu, item.weidu],
              index: item.id
            };
          })
        // 调用地图初始化方法，传入数据
        console.log('+++++'+ pointArray)
        setTimeout(() => {
          initGeoMap(pointArray);
          console.log('+++++'+ pointArray)
        }, 3000)
        console.log('===='+ pointArray)
      },
      error: function (err) {
        console.log('err', err);
      }
    })
  }

  // ************* 地图全屏切换操作
  $('#btn-toggle').click(function () {
    if ($('.middle-map').hasClass("middle-map-full")) {
      $('.middle-map').removeClass("middle-map-full");
      $('.aside-left').show(300);
      $('.aside-right').show(300);
      $(this).attr('title', '全屏展示');
      $(this).html('<img src="./img/index/expand.png" alt="全屏展示"/><p>全屏</p>');
    } else {
      $('.middle-map').addClass("middle-map-full");
      $('.aside-left').slideToggle(300);
      $('.aside-right').slideToggle(300);
      $(this).attr('title', '取消全屏');
      $(this).html('<img src="./img/index/small.png" alt="取消全屏"/><p>返回</p>');
    }
    var myChart = echarts.init(document.getElementById('map'));
    myChart.resize();
    getAllShopList();
  });

  // ********* 页面初始化调用
  getAllShopList();
});